package com.crm.common.utils;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

/**
 * 地址工具类 - 根据IP获取地理位置信息
 */
public class AddressUtils {
    private static final Logger log = LoggerFactory.getLogger(AddressUtils.class);

    // 使用淘宝IP库接口（实际项目中建议替换为自己的服务或商业API）
    public static final String IP_URL = "http://ip.taobao.com/service/getIpInfo.php";

    // 未知地址标识
    public static final String UNKNOWN = "XX XX";

    /**
     * 根据IP获取真实地理位置
     *
     * @param ip IP地址
     * @return 地理位置描述
     */
    public static String getRealAddressByIP(String ip) {
        if (IpUtils.isInternalIp(ip)) {
            return "内网IP";
        }

        try {
            String rspStr = sendRequest(IP_URL + "?ip=" + ip);
            if (StringUtils.isEmpty(rspStr)) {
                log.error("获取地理位置异常 {}", ip);
                return UNKNOWN;
            }

            JSONObject obj = JSON.parseObject(rspStr);
            if (obj.getIntValue("code") == 0) {
                JSONObject data = obj.getJSONObject("data");

                String region = data.getString("region");
                String city = data.getString("city");
                String isp = data.getString("isp");

                return String.format("%s %s %s", region, city, isp);
            } else {
                log.error("获取地理位置异常 {}", ip);
                return UNKNOWN;
            }
        } catch (Exception e) {
            log.error("获取地理位置异常 {}", ip, e);
            return UNKNOWN;
        }
    }

    /**
     * 发送HTTP请求获取IP信息
     */
    private static String sendRequest(String url) throws Exception {
        HttpURLConnection connection = null;
        BufferedReader reader = null;
        try {
            URL realUrl = new URL(url);
            connection = (HttpURLConnection) realUrl.openConnection();
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(3000);
            connection.setReadTimeout(3000);
            connection.connect();

            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                reader = new BufferedReader(new InputStreamReader(
                        connection.getInputStream(), StandardCharsets.UTF_8));

                StringBuilder result = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    result.append(line);
                }

                return result.toString();
            }
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (Exception e) {
                    log.error("关闭流异常", e);
                }
            }
            if (connection != null) {
                connection.disconnect();
            }
        }
        return null;
    }

    /**
     * 简化版地址获取（离线版本，适合没有网络请求权限的环境）
     */
    public static String getSimpleAddressByIP(String ip) {
        if (IpUtils.isInternalIp(ip)) {
            return "内网IP";
        }

        // 这里可以添加一些简单的IP段判断逻辑

        return UNKNOWN;
    }
}
